import 'package:firebase_message_plugin/firebase_message_plugin.dart';
import 'package:business_plugin/utils/business_tools.dart';

// 后台消息处理函数
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  BusinessTools.log('Handling a background message: ${message.messageId}');
  BusinessTools.log('Message data: ${message.data}');
  BusinessTools.log('Message notification: ${message.notification?.title}');
}

class FirebaseMessageTools {
  static FirebaseMessageTools? _instance;
  // 单例模式
  static FirebaseMessageTools get instance {
    _instance ??= FirebaseMessageTools._internal();
    return _instance!;
  }

  FirebaseMessageTools._internal();

  final FirebaseMessageService _messageService = FirebaseMessageService.instance;

  // 初始化Firebase Messaging
  Future<void> initFirebaseMessaging() async {
    try {
      // 初始化服务
      await _messageService.initialize();

      // 先检查当前权限状态
      NotificationSettings currentSettings = await _messageService.getNotificationSettings();
      BusinessTools.log('当前权限状态: ${currentSettings.authorizationStatus}');

      NotificationSettings settings;

      // 根据当前状态决定是否需要请求权限
      switch (currentSettings.authorizationStatus) {
        case AuthorizationStatus.notDetermined:
          // 还未请求过权限，现在请求
          BusinessTools.log('首次请求通知权限...');
          settings = await _messageService.requestPermission(alert: true, badge: true, sound: true);
          break;

        case AuthorizationStatus.denied:
          // 用户之前拒绝了，可以再次请求（但要谨慎）
          BusinessTools.log('用户之前拒绝了权限，尝试再次请求...');
          settings = await _messageService.requestPermission(alert: true, badge: true, sound: true);
          break;

        case AuthorizationStatus.authorized:
          // 已经授权，直接使用当前设置
          BusinessTools.log('用户已授权通知权限');
          settings = currentSettings;
          break;

        case AuthorizationStatus.provisional:
          // 临时授权（iOS 12+），可以考虑升级为完全授权
          BusinessTools.log('当前为临时授权，考虑升级为完全授权...');
          settings = await _messageService.requestPermission(
            alert: true,
            badge: true,
            sound: true,
            provisional: false, // 请求完全授权
          );
          break;
      }

      BusinessTools.log('最终权限状态: ${settings.authorizationStatus}');

      // 只有在获得权限后才继续后续操作
      if (settings.authorizationStatus == AuthorizationStatus.authorized ||
          settings.authorizationStatus == AuthorizationStatus.provisional) {
        // 设置后台消息处理器
        FirebaseMessageService.setBackgroundMessageHandler(firebaseMessagingBackgroundHandler);

        // 获取FCM令牌
        String? token = await _messageService.getToken();
        BusinessTools.log('FCM Token: ${token ?? 'Failed to get token'}');

        // 监听令牌刷新
        _messageService.onTokenRefresh.listen((newToken) {
          BusinessTools.log('FCM Token refreshed: $newToken');
        });

        // 处理前台消息
        _messageService.onMessage.listen((RemoteMessage message) {
          BusinessTools.log('Got a message whilst in the foreground!');
          BusinessTools.log('Message data: ${message.data}');

          if (message.notification != null) {
            BusinessTools.log('Message also contained a notification: ${message.notification}');
          }
        });

        // 处理应用从后台打开的消息
        _messageService.onMessageOpenedApp.listen((RemoteMessage message) {
          BusinessTools.log('应用从后台打开的消息: ${message.notification?.title}');
        });

        // 检查应用是否从终止状态通过通知打开
        RemoteMessage? initialMessage = await _messageService.getInitialMessage();
        if (initialMessage != null) {
          BusinessTools.log('通过通知从已关闭状态重新打开了应用程序: ${initialMessage.notification?.title}');
        }
      } else {
        BusinessTools.log('用户未授权通知权限，跳过FCM相关功能');
        // 可以在这里显示一个友好的提示，告诉用户如何在设置中开启权限
      }
    } catch (e) {
      BusinessTools.log('初始化 Firebase 消息服务时出错: $e');
    }
  }

  // 添加一个检查权限的便捷方法
  Future<bool> hasNotificationPermission() async {
    try {
      NotificationSettings settings = await _messageService.getNotificationSettings();
      return settings.authorizationStatus == AuthorizationStatus.authorized ||
          settings.authorizationStatus == AuthorizationStatus.provisional;
    } catch (e) {
      BusinessTools.log('检查权限时出错: $e');
      return false;
    }
  }

  // 添加一个引导用户到设置页面的方法
  Future<void> showPermissionDialog() async {
    // 这里可以显示一个对话框，引导用户到设置中开启权限
    BusinessTools.log('请在设置中开启通知权限以接收重要消息');
  }
}
